package magnetic.field.arduino;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.BufferedReader;
import java.io.IOException;
//import java.io.IOException;
import java.io.InputStreamReader;
//import java.io.OutputStream;

import java.util.Enumeration;



public class Magnetometro implements SerialPortEventListener {
       
SerialPort serialPort;
int x;
int y;
int z,campo = 0;
int cont,cont2 = 0;
int dc1,dc2 = 0; 
int D[][] = new int [3][4];
int E[][][] = new int [3][4][3];



public float getX() {
	return x;
}

public void setX(int x) {
	this.x = x;
}

public float getY() {
	return y;
}

public void setY(int y) {
	this.y = y;
}

public float getZ() {
	return z;
}

public void setZ(int z) {
	this.z = z;
}

public float getCampo() {
	return campo;
}

public void setCampo(int campo) {
	this.campo = campo;
}

		private static final String PORT_NAMES[] = { "COM5" }; // Porta Usada
        // private static final String PORT_NAMES[] = { "/dev/tty.usbmodem411" }; //
       

        private static BufferedReader input;
//        private static OutputStream output;
        private static final int TIME_OUT = 2000; // Milissegundos para bloqueio
                                                                                                // enquanto aguarda a porta
                                                                                                // abrir

        private static final int DATA_RATE = 9600; // baud rate da porta

        public void initialize() {
        	CommPortIdentifier portId = null;
            @SuppressWarnings("rawtypes")
			Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

                while (portEnum.hasMoreElements()) {
                        CommPortIdentifier currPortId = (CommPortIdentifier) portEnum
                                        .nextElement();
                        for (String portName : PORT_NAMES) {
                                if (currPortId.getName().equals(portName)) {
                                        portId = currPortId;
                                        break;
                                }
                        }
                }
                if (portId == null) {
                        System.out.println("\nPorta COM nao encontrada\n");
                        return;
                }

                try {
                        serialPort = (SerialPort) portId.open(this.getClass().getName(),
                                        TIME_OUT);

                        serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8,
                                        SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                        input = new BufferedReader(new InputStreamReader(
                                        serialPort.getInputStream(),"ISO-8859-1"));         // Mudança de codificação padrão UTF-8 ( -127 a 127) para
                        serialPort.addEventListener((SerialPortEventListener) this);// ISO-8859-1 (0 a 255), pois o xbee envia de 0 a 255,
                                                                                                                                                
                        serialPort.notifyOnDataAvailable(true);
                } catch (Exception e) {
                        System.err.println(e.toString());
                }
        }

        /**
         * Deve ser chamado quando voc� parar de usar a porta. Evita travamento de
         * porta em plataformas Linux.
         */
        public synchronized void close() {
                if (serialPort != null) {
                        serialPort.removeEventListener();
                        serialPort.close();
                }
        }
        
        public int comparar(int E[][][],int D[][]) {
        	
        	double P[] = new double[5];
        	int m,posicao=0,n = 0;
        	double x,y,z;
        	double soma[] = new double[3];
        	double menor = 4000;
        	
        	for (n=0;n<3;n++) {
        	for (m=0;m<4;m++){
        		x = D[0][m] - E[n][m][0];
        		y = D[1][m] - E[n][m][1];
        		z = D[2][m] - E[n][m][2];
        		
        		P[m] = Math.sqrt(x*x+y*y+z*z);
        		
        		soma[n] = soma[n] + P[m];
        		
//        		x = D[0][1] - E[0][1][0];
//        		y = D[1][1] - E[0][1][1];
//        		z = D[2][1] - E[0][1][2];
//        		
//        		x = D[0][2] - E[0][2][0];
//        		y = D[1][2] - E[0][2][1];
//        		z = D[2][2] - E[0][2][2];
//        		
//        		x = D[0][3] - E[0][3][0];
//        		y = D[1][3] - E[0][3][1];
//        		z = D[2][3] - E[0][3][2];
        		
        		
        		
        		
        		
        	}
        	if (soma[n] < menor){
    			menor = soma[n];
    			posicao = n;
    		}
        	}
        	
        	
        	return posicao;
        }
        

        public synchronized void serialEvent(SerialPortEvent oEvent) {
        	
        	
                if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                       
                       
                        try {
                        	 
                               
                        	/*
                        	1 = X
                        	2 = Y
                        	3 = Z
                        	4 = Gauss
                        	*/

                        	   String[] parts = input.readLine().split(" ");
                        	   

                        	   if (Integer.parseInt(parts[1]) == 1 && Integer.parseInt(parts[3]) == 2 && Integer.parseInt(parts[5]) == 3) {
                        	   x = Integer.parseInt(parts[0]);
                        	   y = Integer.parseInt(parts[2]);
                        	   z = Integer.parseInt(parts[4]);
                        	  
                        	   if (cont <= 3 && cont2 <=2) {
                        	   System.out.println("X="+x+" Y="+y+" Z="+z+" Linha="+cont2+" Coluna="+cont);
                        	   E[cont2][cont][0] = x;
                    		   E[cont2][cont][1] = y;
                    		   E[cont2][cont][2] = z;
                        	   cont++;
                        	   }
                        	   else  {
                        		   cont = 0;
                        		   cont2++;                       
                        	   }   
                        	   if (cont2 == 3) 
                        		   System.out.println("Array completo");
                        	   if (cont2 >= 3) {
                        		   cont2 = 4;
                        		   
                        		   if (dc1 <= 3) {
                        			 
                        			   D[0][dc1] = x;
                            		   D[1][dc1] = y;
                            		   D[2][dc1] = z;
                                	   System.out.println(dc1);
                            		   dc1++;
                        			   
                        		   }
                        		   
                        		   else {
                        			   
                        			   int posicao = comparar(E,D);
                        			   System.out.println("posição mais proxima = "+posicao);
                        			   dc1 = 0;
                        		   }
                        		   
                        		   
                        		   
                        	   }
                        	   
                        		  // System.out.println("Array Completo");
                        //		   int m,n;
                               	
//                               	for (m=0;m<5;m++){
//                               		for (n=0;n<3;n++){
//                               			System.out.print(M[m][n]+" " );
//                               		}
//                               		System.out.println("");
//                               	}
                               	
                               	
                               	
                              // 	int posicao = comparar(M,P);
                             //  	System.out.println("menor= "+posicao+" X="+x+" Y="+y+" Z="+z+" C="+cont);
                               	
                               	//close();
                               	//System.exit(0);
                        		   
                        	   
                        	   
                        	   
                        	   }
                        	   else {
                        		   
                        		   System.out.println("Dados perdidos, favor apertar o botao novamente");
                        	   }
                        	  
                               
                               
                        } catch (IOException e) {
                                System.err.println(e.toString());

                        }
                        
                        catch (ArrayIndexOutOfBoundsException e) {

                        	
                        	System.out.println("Problema na matriz de mapeamento M");
                        }
                }
        
        }

       
        public static void main(String[] args) {
               

        	
                Magnetometro app = new Magnetometro();
                app.initialize();
               
                

        }
}